package org.jeecg.modules.SellsSavesModule.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.ParameterModule.entity.*;
import org.jeecg.modules.ParameterModule.service.LocationService;
import org.jeecg.modules.SellsSavesModule.entity.*;
import org.jeecg.modules.SellsSavesModule.service.InventoryService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 进销存管理
 * */
@Api(tags="进销存管理")
@RestController
@RequestMapping("/inventory/manger")
@Slf4j
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    /**
     * 入库单的分页列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/instorageDanPagelist")
    public Result<?> query_instorageDanPagelist(@RequestParam(name="pageNo", defaultValue="1") final Integer pageNo,
                                             @RequestParam(name="pageSize", defaultValue="10") final Integer pageSize,
                                             String queryName, String queryCode) {
        Page<InstorageDanInfo> page = new Page<InstorageDanInfo>(pageNo, pageSize);
        IPage<InstorageDanInfo> pageList = inventoryService.query_InstorageDanInfoPageList(page,queryName,queryCode);
        return Result.ok(pageList);
    }
    /**
     * 入库单下的商品的分页列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/instorageDan_goodsPagelist")
    public Result<?> query_instorageDan_goodsPagelist(@RequestParam(name="pageNo", defaultValue="1") final Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") final Integer pageSize,
                                                String topId) {
        Page<InstorageDanGoods> page = new Page<InstorageDanGoods>(pageNo, pageSize);
        IPage<InstorageDanGoods> pageList = inventoryService.query_InstorageDanGoodsPageList(page,topId);
        return Result.ok(pageList);
    }
    /**
     * 商品面料统合表--商品表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/goods_fabricPagelist")
    public Result<?> query_goods_fabricPagelist(@RequestParam(name="pageNo", defaultValue="1") final Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") final Integer pageSize,
                                                String goods_code,String supplierGoodsCode) {
        Page<GoodsInfo> page = new Page<GoodsInfo>(pageNo, pageSize);
        System.out.println("==闯进来="+goods_code);
        IPage<GoodsInfo> pageList = inventoryService.query_GoodsFabricPageList(page,goods_code,supplierGoodsCode);
        return Result.ok(pageList);
    }

    /**
     * 入库商品下的配置项
     * @param pageNo
     * @param pageSize
     * @param type:1查询商品入库项，2查询入库单下的
     * @param topId：上级id
     * @return
     */
    @GetMapping(value = "/ruku_goods_peizhiPagelist")
    public Result<?> ruku_goods_peizhiPagelist(@RequestParam(name="pageNo", defaultValue="1") final Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") final Integer pageSize,
                                               String topId,int type) {
        Page<InstorageItemsInfo> page = new Page<InstorageItemsInfo>(pageNo, pageSize);
        IPage<InstorageItemsInfo> pageList = inventoryService.query_rukuitemsPageList(page,topId,type);
        return Result.ok(pageList);
    }

    /**
     * id查询入库单详情
     * @return
     */
    @GetMapping(value = "/query_InstorageDanById")
    public Result<?> query_InstorageDanById(@RequestParam(name="id")String id){
        InstorageDanInfo datainfo = inventoryService.query_instorageDanById(id);
        if(datainfo!=null){
            return Result.ok(datainfo);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * id查询入库单下的商品详情
     * @return
     */
    @GetMapping(value = "/query_InstorageDan_goodsById")
    public Result<?> query_InstorageDan_goodsById(@RequestParam(name="id")String id){
        InstorageDanGoods datainfo = inventoryService.query_instorageDan_goodsById(id);
        if(datainfo!=null){
            return Result.ok(datainfo);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询所有规格
     * @return
     */
    @GetMapping(value = "/query_specifications_BygoodsId")
    public Result<?> query_specifications_BygoodsId(@RequestParam(name="good_id")String good_id){
        List<GoodsSpecifications> datalist = inventoryService.query_allSpecificationsBygoodId(good_id);
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询所有尺码
     * @return
     */
    @GetMapping(value = "/query_size_BygoodsId")
    public Result<?> query_size_BygoodsId(@RequestParam(name="good_id")String good_id){
        List<GoodsSizeInfo> datalist = inventoryService.query_allSizeBygoodId(good_id);
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询所有仓库
     * @return
     */
    @GetMapping(value = "/query_Warehouselist")
    public Result<?> query_Warehouselist(){
        List<WarehouseInfo> datalist = inventoryService.query_allWarehouse();
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询仓库下的库区
     * @return
     */
    @GetMapping(value = "/query_Reservoir_BytopId")
    public Result<?> query_Reservoir_BytopId(@RequestParam(name="top_id")String top_id){
        List<ReservoirInfo> datalist = inventoryService.query_allReservoirBycangkuId(top_id);
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询库区下的货架
     * @return
     */
    @GetMapping(value = "/query_Shelves_BytopId")
    public Result<?> query_Shelves_BytopId(@RequestParam(name="top_id")String top_id){
        List<ShelvesInfo> datalist = inventoryService.query_allShelvesBykuquId(top_id);
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }
    /**
     * 查询货架下的库位
     * @return
     */
    @GetMapping(value = "/query_Location_BytopId")
    public Result<?> query_Location_BytopId(@RequestParam(name="top_id")String top_id){
        List<LocationInfo> datalist = inventoryService.query_allLocationByhuojiaId(top_id);
        if(datalist.size()>0){
            return Result.ok(datalist);
        }else{
            return Result.error("未找到对应数据");
        }
    }


    /**
     * 修改入库单
     * @param
     * @return boolean
     */
    @PutMapping(value = "/update_instorageDan")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update_instorageDan(@RequestBody InstorageDanInfo testInfo) {
        //获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String sys_org_code = sysUser.getOrgCode();
        String create_by = sysUser.getUsername();
        testInfo.setUpdateBy(create_by);
        testInfo.setSysOrgCode(sys_org_code);
        testInfo.setStatus(0);
        int code = inventoryService.update_InstorageDan(testInfo);
        if(code==0){
            return Result.ok("保存成功");
        }else if(code==1){
            return Result.error("操作失败");
        } else {
            return Result.error("参数错误，请重新添加");
        }
    }

    /**
     * 添加入库单
     */
    @PostMapping("/add_instorageDan")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject add_instorageDan(InstorageDanInfo testInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        //获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String sys_org_code = sysUser.getOrgCode();
        String create_by = sysUser.getUsername();
        Long startTs = System.currentTimeMillis(); // 当前时间戳
        //8位随机数
        int random=new Random().nextInt(1000000)+1;//为变量赋随机值1-99999999;
        int random2=new Random().nextInt(100)+1;
        String dan_id = ""+startTs.toString()+random;
//        String danhaoSn = UUID.randomUUID().toString().substring(0,10)+random2;
        String danhaoSn = "RKD"+startTs.toString()+random2;
        //赋值创建人信息
        testInfo.setId(dan_id);
        testInfo.setCode(danhaoSn);
        testInfo.setCreateBy(create_by);
        testInfo.setSysOrgCode(sys_org_code);
        testInfo.setStatus(0);
        int result = inventoryService.add_InstorageDan(testInfo);
        if (result == 0) {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "新建入库单成功");
            jsonObject.put("instorageDanId", dan_id);
        } else if(result==1){
            jsonObject.put("code", 1);
            jsonObject.put("msg", "新建入库单失败");
        }
        else {
            jsonObject.put("code", 500);
            jsonObject.put("msg", "参数错误");
        }
        return jsonObject;
    }

    /**
     * 添加入库单下的商品
     * @param
     * @return boolean
     */
    @PostMapping(value = "/add_instorageDan_goods")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> add_instorageDan_goods(@RequestBody InstorageDanGoods testInfo) {
        //执行逻辑前先进行非空验证
        if(testInfo.getGoodsId()==null || "".equals(testInfo.getGoodsId())){
            return Result.error("请选择商品");
        }else if(testInfo.getIntoSumnumber()==null || "".equals(testInfo.getIntoSumnumber())){
            return Result.error("请输入入库数量");
        }else if(testInfo.getIntoUnit()==null || "".equals(testInfo.getIntoUnit())){
            return Result.error("请输入入库单价");
        }else {
            //根据入库单id和商品id查询入库单下的商品
            InstorageDanGoods instorageDanGoods = inventoryService.query_instorageDangoodsBygoodId(testInfo.getInstorageDanId(),testInfo.getGoodsId());
            if(instorageDanGoods != null){
                return Result.error("该入库单已有该商品，请勿重复添加");
            }else {
                //获取登录用户信息
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                String sys_org_code = sysUser.getOrgCode();
                String create_by = sysUser.getUsername();
                Long startTs = System.currentTimeMillis(); // 当前时间戳
                //8位随机数
                int random=new Random().nextInt(1000000)+1;//为变量赋随机值1-99999999;
                String danhaoSn = "RKDSP"+startTs.toString()+random;
                //获取输入库存，和单价
                double num = Double.parseDouble(testInfo.getIntoSumnumber()+"");
                double price = Double.parseDouble(testInfo.getIntoUnit());
                double SumMoney = num*price;
                DecimalFormat df = new DecimalFormat("0.00");
                //赋值创建人信息
                testInfo.setCreateBy(create_by);
                testInfo.setSysOrgCode(sys_org_code);
                testInfo.setId(danhaoSn);
                testInfo.setStatus(0);
                testInfo.setIntoMoney(df.format(SumMoney));
                testInfo.setRemainingNumber(num);
                int code = inventoryService.add_InstorageDan_goods(testInfo);
                if(code==0){
                    //修改入库单的状态
                    inventoryService.update_rukudan_status(testInfo.getInstorageDanId(),1);
                    return Result.ok("添加成功");
                }else {
                    return Result.error("添加失败");
                }
            }
        }
    }

    /**
     * 添加入库项
     * @param
     * @return boolean
     */
    @PostMapping(value = "/add_instorageitems")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> add_instorageitems(@RequestBody InstorageItemsInfo testInfo) {
        //执行逻辑前先进行非空验证
        if(testInfo.getBatchName()==null || "".equals(testInfo.getBatchName())){
            return Result.error("批次批号不能为空");
        }else if(testInfo.getGoodsSpecificationsId()==null || "".equals(testInfo.getGoodsSpecificationsId())){
            return Result.error("请选择规格");
        }else if(testInfo.getGoodsSizeId()==null || "".equals(testInfo.getGoodsSizeId())){
            return Result.error("请选择尺码");
        }else if(testInfo.getIncount()==null || "".equals(testInfo.getIncount())){
            return Result.error("请输入入库数量");
        }else if(testInfo.getLocationId()==null || "".equals(testInfo.getLocationId())){
            return Result.error("请选择库位");
        }else {
            //根据库位id查询批次
            InstorageItemsInfo itemsInfo = inventoryService.query_InstorageItemsBylocationId(testInfo.getLocationId());
            if(itemsInfo!=null){
                return Result.error("该库位已被占用，请选择其它库位");
            }
            double sum_num = 0.00;
            double remaining_num = 0.00;
            //输入的库存
            double incount = Double.parseDouble(testInfo.getIncount());
            //根据入库单下的商品关联id查询详情
            InstorageDanGoods instorageGoodsDetail = inventoryService.query_instorageDan_goodsById(testInfo.getInstorageGoodsId());
            if(instorageGoodsDetail != null){
                sum_num = instorageGoodsDetail.getRemainingNumber();
            }
            if(incount>sum_num){
                return Result.error("剩余库存不足");
            }
            //计算剩余库存
            remaining_num = sum_num-incount;
            DecimalFormat df = new DecimalFormat("0.00");
            //获取登录用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String sys_org_code = sysUser.getOrgCode();
            String create_by = sysUser.getUsername();
            Long startTs = System.currentTimeMillis(); // 当前时间戳
            //8位随机数
            int random=new Random().nextInt(1000000)+1;//为变量赋随机值1-99999999;
            String danhaoId = "RKITEMS"+startTs.toString()+random;
            String bianhaocode = UUID.randomUUID().toString().substring(0,12)+random;
            //赋值创建人信息
            testInfo.setCreateBy(create_by);
            testInfo.setSysOrgCode(sys_org_code);
            testInfo.setId(danhaoId);
            testInfo.setStatus(0);
            testInfo.setCode(bianhaocode);
            int code = inventoryService.add_Instorageitems(testInfo);
            if(code==0){
                //执行修改剩余入库
                inventoryService.update_instoragegood_count(testInfo.getInstorageGoodsId(),df.format(remaining_num));
                //修改入库单下的商品状态
                inventoryService.delete_InstorageDan_goods(testInfo.getInstorageGoodsId(),"1");
                return Result.ok("添加成功");
            }else {
                return Result.error("添加失败");
            }
        }
    }

    /**
     * 删除/撤销入库项
     * @param
     * @return boolean
     */
    @PutMapping(value = "/change_instorageitems_status")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> change_instorageitems_status(@RequestBody Map<String,Object> params) {
        String id = params.get("id").toString();
        String status = params.get("status").toString();
        try {
            int code = inventoryService.delete_Instorageitems(id,status);
            int code2 = 0;
            //根据id查询入库项详情
            InstorageItemsInfo instorageItemsInfo = inventoryService.query_InstorageItemsInfoById(id);
            if(instorageItemsInfo!=null) {
                //拿到库存
                double nownum = Double.parseDouble(instorageItemsInfo.getIncount());
                double incount = 0.00;
                //查询老的库存
                InstorageDanGoods datainfo = inventoryService.query_instorageDan_goodsById(instorageItemsInfo.getInstorageGoodsId());
                if(datainfo!=null){
                    incount = datainfo.getRemainingNumber();
                }
                double oldNum = nownum+incount;
                DecimalFormat df = new DecimalFormat("0.00");
                String syNum = df.format(oldNum);
                //把入库单下的商品下的剩余库存还原回去
                code2 = inventoryService.update_instoragegood_count(instorageItemsInfo.getInstorageGoodsId(),syNum);
            }
            if(code==0 && code2==0){
                return Result.ok("操作成功");
            }else {
                return Result.error("操作失败");
            }
        }catch (Exception e){
            return Result.error("操作失败，参数错误");
        }
    }

    /**
     * 删除/撤销入库申请单下的商品
     * @param
     * @return boolean
     */
    @PutMapping(value = "/change_instoragegoods_status")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> change_instoragegoods_status(@RequestBody Map<String,Object> params) {
        String id = params.get("id").toString();
        String status = params.get("status").toString();
        try {
            int code = inventoryService.delete_InstorageDan_goods(id,status);
            if(code==0){
                return Result.ok("操作成功");
            }else {
                return Result.error("操作失败");
            }
        }catch (Exception e){
            return Result.error("操作失败，参数错误");
        }
    }

    /**
     * 完成入库---往库存表里面添加或者修改
     * @param
     * @return boolean
     */
    @PostMapping(value = "/finish_instorage_intokucun")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> finish_instorage_intokucun(@RequestBody InstorageItemsInfo testInfo) {
        //获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String sys_org_code = sysUser.getOrgCode();
        String create_by = sysUser.getUsername();
        DecimalFormat df = new DecimalFormat("0.00");
        int code1 = 0,code2=0;
        //统计待入库
        int wait_count = inventoryService.count_waitRuku(testInfo.getInstorageDanId(),0);
        if(wait_count>0){
            return Result.error("还有待入库，请先确认入库");
        }else {
            String inventoryId = "";
            //根据入库申请单id查询下面所有的入库项-根据商品id分组
            List<InstorageItemsInfo> instorageItemsInfoList = inventoryService.query_allInstorageItemsByrukudanId(testInfo.getInstorageDanId(),0);
            if(instorageItemsInfoList.size()>0){
                for (int i = 0;i<instorageItemsInfoList.size();i++){
                    //循环判断
                    InventoryInfo inventoryDateil = inventoryService.query_InventoryInfoBygoodsId(instorageItemsInfoList.get(i).getGoodsId());
                    if(inventoryDateil!=null){
                        //拿到原先的总库存
                        double oldcount = Double.parseDouble(inventoryDateil.getSumCount());
                        double incount = Double.parseDouble(instorageItemsInfoList.get(i).getIncount());
                        double sum = oldcount+incount;
                        inventoryId = inventoryDateil.getId();
                        //执行修改
                        InventoryInfo datainfo = new InventoryInfo();
                        datainfo.setSumCount(df.format(sum));
                        datainfo.setGoodsId(inventoryDateil.getGoodsId());
                        code1 = inventoryService.update_inventory(datainfo);
                    }else {
                        Long startTs = System.currentTimeMillis(); // 当前时间戳
                        //8位随机数
                        int random=new Random().nextInt(1000000)+1;//为变量赋随机值1-99999999;
                        inventoryId = "IY-"+startTs.toString()+random;
                        //根据商品id查询详情
                        GoodsInfo goodsInfo = inventoryService.query_goodsDetailBygoodsId(instorageItemsInfoList.get(i).getGoodsId());
                        //循环插入库存表
                        InventoryInfo inventoryInfo2 = new InventoryInfo();
                        inventoryInfo2.setId(inventoryId);
                        inventoryInfo2.setGoodsId(instorageItemsInfoList.get(i).getGoodsId());
                        inventoryInfo2.setRemark("入库");
                        inventoryInfo2.setSumCount(instorageItemsInfoList.get(i).getIncount());
                        inventoryInfo2.setType(goodsInfo.getIsGood());
                        inventoryInfo2.setWarningCount("0");
                        inventoryInfo2.setStatus(1);
                        inventoryInfo2.setCreateBy(create_by);
                        inventoryInfo2.setSysOrgCode(sys_org_code);
                        code1 = inventoryService.insert_inventory(inventoryInfo2);
                    }
                    /**循环添加商品下面的入库项*/
                        //根据商品id和批次名称查询库存下的批次
                        InventoryBatchInfo inventoryBatchDateil = inventoryService.query_InventoryBatchBygoodsId(instorageItemsInfoList.get(i).getGoodsId(),instorageItemsInfoList.get(i).getBatchName());
                        if(inventoryBatchDateil!=null){
                            double num1 = Double.parseDouble(instorageItemsInfoList.get(i).getIncount());
                            double num2 = Double.parseDouble(inventoryBatchDateil.getNewCount());
                            double sum = num1+num2;
                            //循环修改
                            InventoryBatchInfo batchInfo = new InventoryBatchInfo();
                            batchInfo.setBatchName(instorageItemsInfoList.get(i).getBatchName());
                            batchInfo.setGoodsId(instorageItemsInfoList.get(i).getGoodsId());
                            batchInfo.setNewCount(df.format(sum));
                            code2 = inventoryService.update_inventory_batch(batchInfo);
                        }else {
                            //循环插入库存下的批次表
                            InventoryBatchInfo batchInfo = new InventoryBatchInfo();
                            batchInfo.setId(UUID.randomUUID().toString());
                            batchInfo.setCode(UUID.randomUUID().toString().substring(0,12));
                            batchInfo.setMerchandiseInventoryId(inventoryId);
                            batchInfo.setBatchName(instorageItemsInfoList.get(i).getBatchName());
                            batchInfo.setGoodsId(instorageItemsInfoList.get(i).getGoodsId());
                            batchInfo.setBatchCode(instorageItemsInfoList.get(i).getCode());
                            batchInfo.setStatus(1);
                            batchInfo.setInventoryitemsId(instorageItemsInfoList.get(i).getId());
                            batchInfo.setRukuTime(new Date());
                            batchInfo.setNewCount(instorageItemsInfoList.get(i).getIncount());
                            batchInfo.setCreateBy(create_by);
                            batchInfo.setSysOrgCode(sys_org_code);
                            code2 = inventoryService.insert_inventory_batch(batchInfo);
                        }
                }
                if(code2==0 || code1==0){
                    //修改入库单的状态
                    inventoryService.update_rukudan_status(testInfo.getInstorageDanId(),2);
                    return Result.ok("审核成功");
                }else {
                    return Result.ok("审核失败");
                }

            }else {
                return Result.error("请添加入库项");
            }
        }
    }

}
